package com.lvmama.config.annotation;

import com.lvmama.config.common.Constant;
import com.lvmama.config.common.ZooKeeperConfigProperties;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.beans.factory.config.BeanFactoryPostProcessor;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;

import java.io.UnsupportedEncodingException;
import java.lang.reflect.Field;

/**
 * Created by troy on 2016/8/31.
 * kouhongyu@163.com
 */
public class ZooKeeperConfigPropertyProcessor implements BeanFactoryPostProcessor {

    public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {
        /**
         * 动态监听开关
         */
        Constant.watcherEnabled = true;
        ZooKeeperConfigProperties.setBeanFactory(beanFactory);

        try {
            for (String beanName : beanFactory.getBeanDefinitionNames()) {

                BeanDefinition beanDefinition = beanFactory.getBeanDefinition(beanName);

                if (!beanDefinition.isAbstract()) {

                    Object object = beanFactory.getBean(beanName);
                    Field[] fields = object.getClass().getDeclaredFields();

                    if (fields != null && fields.length > 0) {
                        for (Field field : fields) {
                            ZooKeeperConfigProperty propertyAnnotation = field.getAnnotation(ZooKeeperConfigProperty.class);

                            if (propertyAnnotation != null) {
                                ZooKeeperConfigProperties.putWatcherBeanField(propertyAnnotation.key(), beanName, field.getName(),field.getType());
                            }
                        }
                    }
                }
            }
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
    }
}
